/*
 * Copyright (C) 2008  Marcelo Busico <marcelobusico@simbya.com.ar>
 * 
 * This file is part of a SIMBYA project.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package gecom.app.configuracion;

import java.io.IOException;
import javax.swing.*;
import javax.swing.text.InternationalFormatter;
import simbya.framework.appserver.ServerConf;
import simbya.framework.excepciones.ConexionFallidaException;
import simbya.framework.excepciones.FaltanDatosRequeridosException;
import simbya.framework.validadores.TextValidator;

/**
 * Ventana para configurar el sistema.
 * @author Marcelo Busico
 */
public class VentanaConfigurarConexion extends javax.swing.JFrame {

    private GestorConfigurarConexion gestor;
    private String servidor;
    private int puerto;

    /**
     * Crea una nueva ventana de la clase VentanaConfigurarConexion
     */
    public VentanaConfigurarConexion(GestorConfigurarConexion gestor) {
        this.gestor = gestor;
        initComponents();
    }

    /**
     * Muestra la configuración en la ventana.
     * @param sdb Objeto con información sobre la conexión a la BD.
     */
    public void mostrarConfiguracion(ServerConf sc) {
        servidor = sc.getDireccion();
        txtServidor.setText(servidor);

        puerto = sc.getPuerto();
        txtPuerto.setValue(new Integer(puerto));
    }

    public void tomarConfirmacion() {
        //Informa al gestor de la confirmación
        try {
            gestor.tomarConfirmacion(new ServerConf(servidor, puerto));
        } catch (ConexionFallidaException cfe) {
            JOptionPane.showMessageDialog(this, "Error al conectar al servidor.\n" +
                    "Alguno de los datos es incorrecto o bien el servidor no está disponible.",
                    "Error", JOptionPane.ERROR_MESSAGE, null);
            return;
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(this,
                    "Error al guardar en archivo de configuración local: " +
                    ioe.getMessage(), "Error", JOptionPane.ERROR_MESSAGE, null);
            return;
        } catch (FaltanDatosRequeridosException fdre) {
            JOptionPane.showMessageDialog(this,
                    "Por favor complete los siguientes datos requeridos: " +
                    fdre.getMessage());
            return;
        }

        //Fin con éxito
        JOptionPane.showMessageDialog(this, "Conexión probada y guardada con éxito.\n" +
                "Reinicie el sistema para aplicar los cambios efectuados.",
                "Información", JOptionPane.INFORMATION_MESSAGE, null);

        gestor.finalizar();
    }

    public void tomarCancelacion() {
        JOptionPane.showMessageDialog(this, "No se han guardado los cambios realizados.",
                "Información", JOptionPane.INFORMATION_MESSAGE, null);
        gestor.finalizar();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnAceptar = new javax.swing.JButton();
        panelServidorDB = new javax.swing.JPanel();
        lblServidor = new javax.swing.JLabel();
        txtServidor = new javax.swing.JTextField();
        lblPuerto = new javax.swing.JLabel();
        InternationalFormatter formatPuerto = new InternationalFormatter();
        formatPuerto.setMinimum(new Integer(0));
        formatPuerto.setMaximum(new Integer(65536));
        txtPuerto = new JFormattedTextField(formatPuerto);
        txtPuerto.setValue(new Integer(0));
        txtPuerto.setText("");
        btnSalir = new javax.swing.JButton();

        setTitle("Configuración del Servidor..."); // NOI18N
        setResizable(false);
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentHidden(java.awt.event.ComponentEvent evt) {
                formComponentHidden(evt);
            }
        });

        btnAceptar.setText("Aceptar");
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        panelServidorDB.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Servidor de Aplicaciones:", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 12))); // NOI18N

        lblServidor.setText("Servidor (Nombre o IP)");

        txtServidor.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtServidorFocusLost(evt);
            }
        });

        lblPuerto.setText("Puerto TCP");

        txtPuerto.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);
        txtPuerto.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtPuertoFocusLost(evt);
            }
        });

        javax.swing.GroupLayout panelServidorDBLayout = new javax.swing.GroupLayout(panelServidorDB);
        panelServidorDB.setLayout(panelServidorDBLayout);
        panelServidorDBLayout.setHorizontalGroup(
            panelServidorDBLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelServidorDBLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelServidorDBLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblServidor)
                    .addComponent(lblPuerto))
                .addGap(7, 7, 7)
                .addGroup(panelServidorDBLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtPuerto, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtServidor, javax.swing.GroupLayout.DEFAULT_SIZE, 168, Short.MAX_VALUE))
                .addContainerGap())
        );
        panelServidorDBLayout.setVerticalGroup(
            panelServidorDBLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelServidorDBLayout.createSequentialGroup()
                .addGroup(panelServidorDBLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblServidor)
                    .addComponent(txtServidor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelServidorDBLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtPuerto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblPuerto))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btnSalir.setText("Cancelar");
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(panelServidorDB, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnAceptar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSalir)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelServidorDB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSalir)
                    .addComponent(btnAceptar))
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-384)/2, (screenSize.height-168)/2, 384, 168);
    }// </editor-fold>//GEN-END:initComponents
    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
        tomarConfirmacion();
}//GEN-LAST:event_btnAceptarActionPerformed

    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
        tomarCancelacion();
    }//GEN-LAST:event_btnSalirActionPerformed

    private void txtPuertoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPuertoFocusLost
        puerto = TextValidator.validarInt(this, txtPuerto, "Puerto de Conexión");
    }//GEN-LAST:event_txtPuertoFocusLost

    private void txtServidorFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtServidorFocusLost
        servidor = txtServidor.getText();
    }//GEN-LAST:event_txtServidorFocusLost

    private void formComponentHidden(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentHidden
        tomarCancelacion();
    }//GEN-LAST:event_formComponentHidden
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnSalir;
    private javax.swing.JLabel lblPuerto;
    private javax.swing.JLabel lblServidor;
    private javax.swing.JPanel panelServidorDB;
    private javax.swing.JFormattedTextField txtPuerto;
    private javax.swing.JTextField txtServidor;
    // End of variables declaration//GEN-END:variables
}
